package controller;

import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * @author  sara
 */
public class ConnectionHandler {
	
	static final String HOST = "127.0.0.1";
	static final int PORT = 1025;
	
	private String host;
	private int port;
	private Socket clientSocket;
	/**
	 * @uml.property  name="connected"
	 */
	private boolean connected;
	
	public ConnectionHandler(){
		this.host = HOST;
		this.port = PORT;
		this.connected = false;
		
	}
	
	public ConnectionHandler(String host, int port){
		this.host = host;
		this.port = port;
		this.connected = false;
		
	}
	
	//inizializza la socket con host e porta predefinita
	public void start(){
		try{
			this.clientSocket = openConnection(HOST, PORT);
			System.out.println("...Connected");
		}  catch (UnknownHostException he){
			//TODO
			System.out.println("Host sconosciuto " + he);
		} catch (IOException ioe){
			//TODO
			System.out.println("Errore di IO " + ioe);
		}
	}
	
	//inizializza la socket con host e porta forniti
	public void start(String host, int port){
		try{
			this.clientSocket = openConnection(host, port);
			System.out.println("...Connected");
		}  catch (UnknownHostException e){
			//TODO
			System.out.println("Host sconosciuto " + e);
		} catch (IOException e){
			//TODO
			System.out.println("Errore di IO " + e);
		}
	}
	
	//chiude la socket creata
	public void stop(){
		try {
			clientSocket.close();
		} catch (IOException e) {
			// TODO 
			System.out.println("impossibile chiudere la connessione " + e);
			e.printStackTrace();
		}
	}
	
	public void request(){}
	public void respond(){}
	
	/**
	 * @return
	 * @uml.property  name="connected"
	 */
	public boolean isConnected(){
		return connected;
	}
	
	private Socket openConnection(String host, int port) throws UnknownHostException, IOException {
		return new Socket(host, port);
	}
	
}
